//
//  SEGShowPhotoView.m
//  Uhomebk
//
//  Created by wangmingmin on 2017/10/25.
//  Copyright © 2017年 com.segi. All rights reserved.
//

#import "SEGShowPhotoView.h"
@interface SEGShowPhotoView () <UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView *imgScrollView;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (strong, nonatomic)UIPageControl * pageControl;
@end

@implementation SEGShowPhotoView
{
    NSMutableArray <UIImage *>* imagesChangeArray;//用于返回数据，比如删除图片等操作后获取新的图片数据等
    NSInteger pageNumber;//当前页,默认为0,首先展示第一张,可更改
    UITapGestureRecognizer *tap;
    UIView * viewNavItem;
    NSInteger selectIndex;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    // 设置返回按钮样式
    UIImage* image = [[UIImage imageWithContentsOfFile:SEGPicName(@"back")] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:image forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    [backBtn addTarget:self action:@selector(DeleteSelf) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.leftBarbuttonWidth = image.size.width;
}

-(instancetype)initWithImageUrls:(NSArray *)imageUrls writable:(NSString *)writable
{
    self = [super init];
    if (self) {
        pageNumber = 0;
        if ([writable isEqualToString:@"1"]) {
            //导航栏的左边按钮
            UIButton* rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
            [rightButton setTitle:@"删除" forState:UIControlStateNormal];
            rightButton.titleLabel.font = kFont_13;
            NSDictionary* attribute = @{ NSFontAttributeName : rightButton.titleLabel.font};
            CGSize textSize = [@"删除" boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 0)
                                                  options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                               attributes:attribute context:nil].size;
            rightButton.frame = CGRectMake(0, 0, textSize.width, 41);
            [rightButton setTitleColor:kColor_T forState:UIControlStateNormal];
            [rightButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -13)];
            [rightButton addTarget:self
                            action:@selector(onNavigationRightButtonClicked:)
                  forControlEvents:UIControlEventTouchUpInside];
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
                    
        }
        selectIndex = 0;
        _imageArray = (NSMutableArray *)imageUrls;
        self.title = [NSString stringWithFormat:@"1/%ld",(unsigned long)_imageArray.count];
        [self setupUI];
    }
    return self;
}

/**
 删除按钮点击事件
 */
- (void)onNavigationRightButtonClicked:(UIButton*)sender
{
    [_imageArray removeObjectAtIndex:selectIndex];
    //回调
    if (self.delegate && [self.delegate respondsToSelector:@selector(didDeletePhotoImage:)]) {
        [self.delegate didDeletePhotoImage:_imageArray];
    }
    [self.imgScrollView removeFromSuperview];
    selectIndex = 0;
    self.title = [NSString stringWithFormat:@"1/%ld",(unsigned long)_imageArray.count];
    [self setupUI];
    if (_imageArray.count == 0) {
        [self.navigationController popViewControllerAnimated:NO];
    }
    
}

-(void)setupUI
{
    self.imgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight()-kNavigationBarAndStatusBarHeight)];
    self.imgScrollView.delegate = self;
    self.imgScrollView.backgroundColor = [UIColor blackColor];
    self.imgScrollView.pagingEnabled = YES;
    self.imgScrollView.contentSize = CGSizeMake(LYScreenWidth()* _imageArray.count, self.imgScrollView.frame.size.height);
    
    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(DeleteSelf)];
    self.imgScrollView.userInteractionEnabled = YES;
    [self.imgScrollView addGestureRecognizer:tap];
    
    self.imgScrollView.contentOffset = CGPointMake(pageNumber*LYScreenWidth(), self.imgScrollView.contentOffset.y);
    [self.view addSubview:self.imgScrollView];
    
    for (int i=0; i< _imageArray.count; i++) {
        NSString * imageUrl = _imageArray[i];
        //1.先看下本地有没有这个图片
        UIImage *localImage = [UIImage imageWithContentsOfFile:imageUrl];
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight()-kNavigationBarAndStatusBarHeight)];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        if (localImage) {
            [imageView setImage:localImage];
        }
        //2.没有本地图片去网络取
        else{
            [imageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kClientImageRootURL,imageUrl]] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_300_300")]];
        }
        UIScrollView * scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(self.imgScrollView.frame.size.width*i+5, 0, self.imgScrollView.frame.size.width-10, self.imgScrollView.frame.size.height)];
        scrollView.tag = i;
        [self scrollview:scrollView AddScaleImageView:imageView];
        [self.imgScrollView addSubview:scrollView];
    }
}
static const CGFloat heightNavgation = 64;
-(void)addNavgationWithTitle:(NSString *)title
{
    NSInteger originY = 20;
    viewNavItem = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), heightNavgation)];
    viewNavItem.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    [self.view addSubview:viewNavItem];
    
    UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, originY, LYScreenWidth(), heightNavgation-originY)];
    titleLabel.backgroundColor = [UIColor clearColor];
    [titleLabel setText:title];
    titleLabel.font = kFont_18;
    titleLabel.textColor = kColor_W;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [viewNavItem addSubview:titleLabel];
    
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, originY, 70, heightNavgation-originY)];
    backBtn.backgroundColor = [UIColor clearColor];
    [backBtn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"navBackNor")] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(DeleteSelf) forControlEvents:UIControlEventTouchUpInside];
    [viewNavItem addSubview:backBtn];
    
    [self.imgScrollView removeGestureRecognizer:tap];
    UITapGestureRecognizer *newTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(HideNavgation)];
    [self.imgScrollView addGestureRecognizer:newTap];
    
}

-(void)HideNavgation
{
    [UIView animateWithDuration:0.2 animations:^{
        CGRect rect = viewNavItem.frame;
        rect.origin.y = rect.origin.y==0? -heightNavgation:0;
        viewNavItem.frame = rect;
    }];
}

static const CGFloat MAX_SCALE = 1.0;
-(void)scrollview:(UIScrollView *)scrollView AddScaleImageView:(UIImageView *)scaleImageView
{
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    
    float horizontalScale = scrollView.frame.size.height / scaleImageView.frame.size.height;
    float verticalScale = scrollView.frame.size.width / scaleImageView.frame.size.width;
    float min = MIN(horizontalScale, verticalScale);
    
    float max = MAX(min, MAX_SCALE);//再次比较，万一图片长宽都小于屏幕
    min = MIN(min, MAX_SCALE);//再次判断，万一图片长宽都小于屏幕
    
    scrollView.minimumZoomScale = min;
    scrollView.maximumZoomScale = max;
    scrollView.delegate = self;
    [scrollView addSubview:scaleImageView];
    
    if (max == MAX_SCALE) {
        scaleImageView.transform = CGAffineTransformScale(scaleImageView.transform, min, min);//刚刚出现时缩放成屏幕可以浏览的尺寸
    }
    scaleImageView.center = CGPointMake(scrollView.frame.size.width/2.0, scrollView.frame.size.height/2.0);
}

#pragma  mark UIScrollViewDidScrolldelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    if (scrollView != self.imgScrollView) {
        NSInteger i = scrollView.tag;
        UIScrollView * scrollViewZoom = self.imgScrollView.subviews[i];
        UIImageView * scaleImageView = scrollViewZoom.subviews.firstObject;
        return scaleImageView;
    }
    return nil;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offset = scrollView.contentOffset.x;
    selectIndex =  offset/LYScreenWidth();
    self.title = [NSString stringWithFormat:@"%ld/%ld",selectIndex+1,_imageArray.count];
    
}
//实现图片在缩放过程中居中
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    if (scrollView != self.imgScrollView) {
        
        NSInteger i = scrollView.tag;
        UIScrollView * scrollViewZoom = self.imgScrollView.subviews[i];
        UIImageView * scaleImageView = scrollViewZoom.subviews.firstObject;
        CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?(scrollView.bounds.size.width - scrollView.contentSize.width)/2 : 0.0;
        CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?(scrollView.bounds.size.height - scrollView.contentSize.height)/2 : 0.0;
        
        scaleImageView.center = CGPointMake(scrollView.contentSize.width/2 + offsetX,scrollView.contentSize.height/2 + offsetY);//先定下中心
        
        scrollView.contentSize = CGSizeMake(scrollView.contentSize.width+offsetX, scrollView.contentSize.height+offsetY);//要显示类容的大小
    }
}

-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    //解决事件响应问题(在大scrollView滑动时候禁止内嵌scrollView滑动，否则经常会有无法翻页的bug)
    if (scale<=scrollView.minimumZoomScale) {
        scrollView.scrollEnabled = NO;
    }else{
        scrollView.scrollEnabled = YES;
    }
}

-(void)DeleteSelf{
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:NO];
        return;
    }
    [self dismissViewControllerAnimated:NO completion:nil];
    
}

- (void)onNavigationLeftButtonClicked:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:NO];
}
@end

